//
//  BaseTextView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/4/21.
//

import UIKit
import RxSwift
class BaseTextView: UITextView {
    private lazy var disposeBag = DisposeBag()

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        //监听字体变化
        Constant.standardViewFlagSuject.subscribe { [weak self] _ in
            guard let strongSelf = self else {return}
            strongSelf.setRealFontSize(strongSelf.font)
        }.disposed(by: self.disposeBag)
    }
    //MARK: - 正常设置font
    func setFont(_ font: UIFont?) {
        if let font = font {
            if Constant.standardViewFlag {
                self.font = font
            }else{
                self.font = font.withSize(font.pointSize * Constant.magnifiedViewScale)
            }
            
        }
    }
    //MARK: - 设置内容按照byWordWrapping
    func setAttributedString(content: String,font: UIFont? = R.font.interRegular(size: 15)){
        let attributedString = NSMutableAttributedString(string: content)
        //字体大小
        if let font = font {
            let realFont = (Constant.standardViewFlag ?  font : font.withSize(font.pointSize * Constant.magnifiedViewScale))
            let attrFont: [NSMutableAttributedString.Key: Any] = [.font: realFont as Any]
            attributedString.addAttributes(attrFont, range: NSRange(location: 0, length: content.count))
        }
        //换行
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineBreakMode = .byWordWrapping
        attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))
        self.attributedText = attributedString
    }
    //MARK: - 设置真正的size
    private func setRealFontSize(_ font: UIFont?){
        if let font = font {
            self.font = font.withSize(font.pointSize * Constant.currentSizeScale)
        }
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
